

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class MenuServer {
	//201521123059
	public static void menu(Scanner in, PrintWriter out, Socket incoming) throws Exception {
		out.println("1-Time");
		out.println("2-IP");
		out.println("3-File");
		out.println("4-quit menu");
		while (in.hasNextLine()) {
			String line = in.nextLine();
			if (line.trim().equals("1")) {
				Date now = new Date();
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd  HH:mm:ss");
				String time = dateFormat.format(now);
				out.println(time);
			}
			if (line.trim().equals("2")) {
				out.println("your ip and port: " + incoming.getInetAddress() + ":" + incoming.getPort());
			}
			if (line.trim().equals("3")) {
				out.println("input filename you want to search:");
				String filename = in.next();
				FindFile.findFile1("D:\\test", filename, out);
			}
			if (line.trim().equals("4")) {
				break;
			}
		}
	}
	
	//201521123059
	public static void main(String[] args) throws Exception {
		/*
		try
		{
			ServerSocket s = new ServerSocket(8190);
			int i = 1;
			while(true){
				Socket incoming = s.accept();
				System.out.println("Spawning " + i);
				Runnable r = new ThreadedEchoHandler(incoming);
				Thread t = new Thread(r);
				t.start();
				i++;
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		*/
		try (DatagramSocket socket = new DatagramSocket(9999);) {
			byte[] buf = new byte[256];
			DatagramPacket packet = new DatagramPacket(buf, buf.length);

			int hello = 1; // 发送初始信息
			while (hello == 1) {
				socket.receive(packet);
				packet.setData("Hello, I am a UDPServer,enter quit to exit, menu to enter ServerMenu\n\n".getBytes());
				socket.send(packet);
				hello = 0;
			}
			while (true) {
				buf = new byte[256];  //假如不重置buf，则会出现消息错乱的可能。
				packet = new DatagramPacket(buf, buf.length);
				socket.receive(packet);
				String data = new String(packet.getData()).trim();
				System.out.println("get a order : " + data);
				if (data.trim().equalsIgnoreCase("quit"))
					break;
				if (data.trim().equals("menu")) {
					MenuServer.udpMenu(socket, packet);
				}
			}
		}
				
	}

	//201521123059
	//udpMenu程序
	public static void udpMenu(DatagramSocket socket, DatagramPacket packet) throws Exception {
		packet.setData("1-Time\n2-IP\n3-File\n4-quit menu\n\n".getBytes());
		socket.send(packet);
		byte[] buf = new byte[256];
		packet = new DatagramPacket(buf, buf.length);
		while (true) {
			buf = new byte[256];
			packet = new DatagramPacket(buf, buf.length);
			socket.receive(packet);
			String data = new String(packet.getData()).trim();
			System.out.println(data);
			if (data.trim().equals("1")) {
				Date now = new Date();
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd  HH:mm:ss");
				String time = dateFormat.format(now) + "\n";
				packet.setData(time.getBytes());
				socket.send(packet);
			}
			if (data.trim().equals("2")){
				String ip = packet.getSocketAddress().toString();
				String msg = "your ip and port: " + ip +"\n";
				packet.setData(msg.getBytes());
				socket.send(packet);
			}
			if (data.trim().equals("3")){
				packet.setData("input filename you want to search:\n".getBytes());
				socket.send(packet);
				buf = new byte[256];
				packet = new DatagramPacket(buf, buf.length);
				socket.receive(packet);
				String filename  = new String(packet.getData()).trim();
				FindFile.findFile1(socket, packet, filename,"D:\\test");
			}
			if (data.trim().equals("4")){
			packet.setData("goodbye!".getBytes());
			socket.send(packet);
				break;
			}
		}
	}
}
//201521123046
//多线程
class ThreadedEchoHandler implements Runnable {
	public ThreadedEchoHandler(Socket i) {
		incoming = i;
	}
	public void run() {
		try {
			try {
				InputStream inStream = incoming.getInputStream();
				OutputStream outStream = incoming.getOutputStream();

				Scanner in = new Scanner(inStream);
				PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);

				out.println("Hello! Enter quit to exit,menu to enter ServerMenu.");

				boolean done = false;
				while (!done && in.hasNextLine()) {
					String line = in.nextLine();
					if (line.trim().equals("quit"))
						done = true;
					if (line.trim().equals("menu")) {
						MenuServer.menu(in, out, incoming);
						out.println("you have just quit ServerMenu.Enter quit to exit,menu to enter ServerMenu");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				incoming.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private Socket incoming;
}
//201521123046
//文件查找
class FindFile {
	static boolean flag = false;

	public static void main(String[] args) throws Exception {
		String path = "D:\\test";
		String filename = "test.txt";

	}
	public static void findFile1(String path, String filename, PrintWriter out) throws Exception {
		findFile(path, filename, out);
		if (!flag)
			System.out.println("Can't find " + filename + " in " + path);
	}
	public static void findFile1(DatagramSocket socket, DatagramPacket packet,String filename,String path) throws Exception {
		
		System.out.println(filename);
		findFile(socket, packet,filename,path);

		if (!flag){
			String msg  = "Can't find " + filename + " in " + path;
			packet.setData(msg.getBytes());
			socket.send(packet);
		}
	}
	public static void findFile(DatagramSocket socket, DatagramPacket packet,String filename,String path) throws IOException{
		File file = new File(path);
		String[] FilesName = file.list();
		for (String FileName : FilesName) {
			File newFile = new File(file.getAbsoluteFile(), FileName);
			if (FileName.equals(filename)) {
				String msg = "Find " + filename + " in:"  + file.getAbsolutePath()+"\n\n";
				packet.setData(msg.getBytes());
				socket.send(packet);
				flag = true;
			}
			if (newFile.isDirectory()) {
				findFile(socket, packet, filename,newFile.getAbsolutePath());
			}
		}
	}//UDPServer FindFile
	public static void findFile(String path, String filename, PrintWriter out) throws Exception {
		File file = new File(path);
		String[] FilesName = file.list();
		if (FilesName.length <= 0) {
			file.delete();
			out.println("delet empty directory: " + file.getAbsolutePath());
		}
		for (String FileName : FilesName) {
			File newFile = new File(file.getAbsoluteFile(), FileName);
			if (FileName.equals(filename)) {
				out.println("Find " + filename + " in:");
				out.println(file.getAbsolutePath());
				flag = true;
				String FileContent = "";
				FileInputStream fis = new
				FileInputStream(newFile.getAbsoluteFile());
				InputStreamReader isr = new InputStreamReader(fis);
				BufferedReader br = new BufferedReader(isr);
				String line = null;
				while ((line = br.readLine()) != null) {
					FileContent += line;
					FileContent += "\r\n";
				}
				FileOutputStream fos = new
				FileOutputStream(newFile.getAbsoluteFile());
				OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
				osw.write(FileContent);
				osw.flush();
				System.out.println(newFile.getAbsoluteFile() + " turn To UTF-8");
			}
			if (newFile.isDirectory()) {
				findFile(newFile.getAbsolutePath(), filename, out);
			}
		}
	}
}